import httpx
import json
from typing import List, Dict, Any
import threading
from loguru import logger as log
import time

# BitBrowser API配置
API_BASE_URL = "http://127.0.0.1:54345"
API_KEY = "eac8901894d94d9382ec40e2129f1b20"
HEADERS = {'Content-Type': 'application/json','x-api-key':'eac8901894d94d9382ec40e2129f1b20'}

# 创建锁，用于线程安全
lock = threading.Lock()

class BitBrowser:
    def __init__(self, id, url=API_BASE_URL, headers=HEADERS):
        self.url = url
        self.headers = headers
        self.id = id
        self.ws = None
        self.context = None
        self.detail = None
        self.is_open = False

    async def open(self, headless=False):
        """打开浏览器"""
        with lock:
            json_data = {"id": self.id}
            async with httpx.AsyncClient() as client:
                response = await client.post(
                    f"{self.url}/browser/open",
                    json=json_data,
                    headers=self.headers
                )
                res = response.json()
                
                if res["success"]:
                    self.ws = res['data']['ws']
                    log.info(f"open browser ws address ==>>> {self.ws}")
                    ret = await self.get_detail()
                    if not ret:
                        return False
                    self.is_open = True
                    time.sleep(2)
                    return True
                else:
                    log.error(res["msg"])
                    return False

    async def close(self):
        """关闭浏览器"""
        with lock:
            json_data = {'id': self.id}
            async with httpx.AsyncClient() as client:
                response = await client.post(
                    f"{self.url}/browser/close",
                    json=json_data,
                    headers=self.headers
                )
                res = response.json()
                
                if res["success"]:
                    log.info(f"close browser success:{self.id}")
                else:
                    log.error(res["msg"])
                self.is_open = False
                time.sleep(3)

    async def get_detail(self):
        """获取浏览器详情"""
        json_data = {"id": self.id}
        async with httpx.AsyncClient() as client:
            response = await client.post(
                f"{self.url}/browser/detail",
                json=json_data,
                headers=self.headers
            )
            res = response.json()
            
            if res["success"]:
                self.detail = res["data"]
                finger_print = self.detail["browserFingerPrint"]["userAgent"]
                log.info(f"get detail success:FingerPrint:{finger_print}")
                return True
            else:
                log.error(res["error"])
                return False

    def get_browser_context(self):
        """获取浏览器上下文"""
        if self.ws:
            port = self.ws.split(':')[2].split('/')[0]
            self.context = f"http://127.0.0.1:{port}"
            return self.context
        return None

async def listBrowser() -> List[Dict[str, Any]]:
    """获取浏览器列表"""
    try:
        json_data = {
            "page": 0,
            "pageSize": 500
        }
        async with httpx.AsyncClient() as client:
            response = await client.post(
                f"{API_BASE_URL}/browser/list",
                json=json_data,
                headers=HEADERS
            )
            res = response.json()
            print(response.content)
            if res["success"] and "data" in res:
                browser_list = res["data"].get("list", [])
                # 按ID倒序排序
                browser_list.sort(key=lambda x: x["id"], reverse=True)
                return browser_list
            return []
    except Exception as e:
        log.error(f"Error fetching browser list: {e}")
        return []

async def openBrowser(browser_id: str) -> Dict[str, Any]:
    """打开指定的浏览器"""
    try:
        browser = BitBrowser(id=browser_id)
        success = await browser.open()
        if success:
            return {"success": True, "message": "浏览器已打开", "data": browser.detail}
        else:
            raise Exception("Failed to open browser")
    except Exception as e:
        log.error(f"Error opening browser: {e}")
        raise Exception(f"Failed to open browser: {str(e)}")

async def createBrowser(name: str, remark: str = "") -> Dict[str, Any]:
    """创建新浏览器"""
    try:
        json_data = {
            "name": name,
            "remark": remark,
            "proxyMethod": 2,
            "proxyType": "noproxy",
            "browserFingerPrint": {
                "coreVersion": "112"
            }
        }
        
        async with httpx.AsyncClient() as client:
            response = await client.post(
                f"{API_BASE_URL}/browser/update",
                json=json_data,
                headers=HEADERS
            )
            res = response.json()
            
            if res["success"]:
                return res["data"]
            else:
                raise Exception(res.get("msg", "Unknown error"))
    except Exception as e:
        log.error(f"Error creating browser: {e}")
        raise Exception(f"Failed to create browser: {str(e)}")
        
        
